import pygame
import os
import time
import threading

import pygame.mixer

def play_audio(file):
    # 初始化pygame的音频模块
    pygame.mixer.init()
    
    if os.path.exists(file):
        # 加载并播放当前音频文件
        print(f"Playing: {file}")
        pygame.mixer.music.load(file)
        pygame.mixer.music.play()
        
        # 等待音频播放完成
        while pygame.mixer.music.get_busy():
            time.sleep(0.1)  # 可以调整为更合适的检测间隔

    # 关闭pygame的音频模块
    pygame.mixer.quit()

def play_audios_sequentially(audio_files):
    # 遍历音频文件列表，为每个文件创建一个新线程来播放
    for file in audio_files:
        thread = threading.Thread(target=play_audio, args=(file,))
        thread.start()
        thread.join()  # 等待当前音频播放完成才继续下一个音频

import pygame
import os
import threading
import time

class AudioPlayer:
    def __init__(self):
        # 初始化pygame音频模块
        pygame.mixer.init()
        self.current_files = []
        self.play_thread = None

    def play_audios(self, audio_files):
        # 检查新的音频列表是否与当前播放的相同
        if set(audio_files) == set(self.current_files) and pygame.mixer.music.get_busy():
            print("Same audio files are already playing.")
            return
        
        # 停止当前播放的音频
        self.stop_audio()
        
        # 更新当前播放列表
        self.current_files = audio_files
        
        # 创建并启动一个新线程来播放音频
        self.play_thread = threading.Thread(target=self.play_audio_sequence, args=(audio_files,))
        self.play_thread.start()

    def play_audio_sequence(self, audio_files):
        for file in audio_files:
            if os.path.exists(file):
                try:
                    print(f"Playing: {file}")
                    pygame.mixer.music.load(file)
                    pygame.mixer.music.play()
                    while pygame.mixer.music.get_busy():
                        time.sleep(0.1)
                except:
                    return
            else:
                print(f"File not found: {file}")

    def stop_audio(self):
        # 停止pygame音乐播放
        pygame.mixer.music.stop()
        pygame.mixer.quit()
        pygame.mixer.init()


    def __del__(self):
        # 清理资源
        pygame.mixer.quit()
        if self.play_thread:
            self.play_thread.join()


if __name__ == "__main__":
    from read_excel import get_datas
    datas = get_datas()

    audios0 = datas[0]["value"]["audios"]
    audios1 = datas[1]["value"]["audios"]

    # play_audios_sequentially(audios0)
    # 示例使用
    player = AudioPlayer()

    player.play_audios(audios0)
    time.sleep(1)
    player.play_audios(audios1)

